<template>
  <div class="member-management">
    <ReCommonTable
      ref="tableRef"
      title="预约订单管理"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :search-fields="searchFields"
      :pagination="pagination"
      @search="handleSearch"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 自定义搜索按钮 -->
      <template #search-buttons>
        <el-button type="primary" @click="handelExport">
          <el-icon>
            <Download />
          </el-icon>
          导出
        </el-button>
      </template>
      <template #toolbar-add>
        <el-radio-group
          v-model="tabPosition"
          size="small"
          class="toolbar-radio-group"
        >
          <el-radio-button
            label="今日"
            value="0"
            @click="() => handleTimeRangeClick(0)"
          />
          <el-radio-button
            label="3天"
            value="3"
            @click="() => handleTimeRangeClick(3)"
          />
          <el-radio-button
            label="5天"
            value="5"
            @click="() => handleTimeRangeClick(5)"
          />
          <el-radio-button
            label="7天"
            value="7"
            @click="() => handleTimeRangeClick(7)"
          />
          <el-radio-button
            label="1个月"
            value="30"
            @click="() => handleTimeRangeClick(30)"
          />
        </el-radio-group>
      </template>
      <!-- 操作列 -->
      <template #action="{ row }">
        <el-button size="small" @click="handleView(row)"> 查看</el-button>
      </template>
    </ReCommonTable>

    <!-- 会员详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="订单详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrder" class="member-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单ID">
            {{ currentOrder.l_id }}
          </el-descriptions-item>
          <el-descriptions-item label="订单编号">
            {{ currentOrder.l_no }}
          </el-descriptions-item>
          <el-descriptions-item label="客户id">
            {{ currentOrder.l_mid || "未填写" }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentOrder.l_mname }}
          </el-descriptions-item>
          <el-descriptions-item label="客户手机" :span="2">
            {{ currentOrder.mobile_val }}
          </el-descriptions-item>
          <el-descriptions-item label="技师id">
            {{ currentOrder.l_jmid }}
          </el-descriptions-item>
          <el-descriptions-item label="技师名称">
            {{ currentOrder.jname }}
          </el-descriptions-item>
          <el-descriptions-item label="项目id">
            {{ currentOrder.l_pid }}
          </el-descriptions-item>
          <el-descriptions-item label="项目名称">
            {{ currentOrder.l_pname }}
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">
            {{ formatTimestamp(currentOrder.l_yytime) }}
          </el-descriptions-item>
          <el-descriptions-item label="单个时长">
            {{ formatSecondsToMinutes(currentOrder.l_project_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="总时长">
            {{ formatSecondsToMinutes(currentOrder.l_totaltime) }}
          </el-descriptions-item>
          <el-descriptions-item label="单价">
            ￥{{ currentOrder.l_price }}
          </el-descriptions-item>
          <el-descriptions-item label="数量">
            {{ currentOrder.l_num }}
          </el-descriptions-item>
          <el-descriptions-item label="总价">
            ￥{{ currentOrder.l_prices }}
          </el-descriptions-item>
          <el-descriptions-item label="预约日期" :span="2">
            {{ currentOrder.yydate_show }}
          </el-descriptions-item>
          <el-descriptions-item label="预约状态" :span="2">
            {{ currentOrder.yuyue_status }}
          </el-descriptions-item>
          <el-descriptions-item label="支付状态" :span="2">
            {{ currentOrder.pay_status }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentOrder.l_remark || "无" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h, effect } from "vue";
import { ElMessage, ElTag } from "element-plus";
import { ReCommonTable } from "@/components/ReCommonTable";
import type {
  SearchField,
  TableColumn
} from "@/components/ReCommonTable/src/index.vue";
import {
  getOrderList,
  exportOrderData,
  type Order,
  type OrderListParams
} from "@/api/order";
import { Plus, Download } from "@element-plus/icons-vue";

defineOptions({
  name: "OrderList"
});

// 响应式数据
const loading = ref(false);
const detailVisible = ref(false);
const tableRef = ref();
const selectedRows = ref([]);
const currentOrder = ref<Order | null>(null);
const tabPosition = ref("0"); // 用于记录当前选中的时间范围
// 搜索表单
const searchForm = ref<OrderListParams>({});

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
  disabled: false,
  paginationSize: "default"
});

// 搜索字段配置（根据API文档）
const searchFields: SearchField[] = [
  {
    prop: "keys",
    label: "关键字",
    type: "input",
    placeholder: "请输入项目、手机号或手机号后4位"
  },
  {
    prop: "status",
    label: "状态",
    type: "select",
    options: [
      { label: "全部", value: "" },
      { label: "未到店", value: 1 },
      { label: "已到店", value: 2 },
      { label: "已超时", value: 3 },
      { label: "已取消", value: 4 }
    ]
  },
  {
    prop: "start_date",
    label: "预约开始日期",
    type: "date",
    placeholder: "开始日期"
  },
  {
    prop: "end_date",
    label: "预约结束日期",
    type: "date",
    placeholder: "结束日期"
  }
];
// 表格列配置（根据API文档字段）
const columns: TableColumn[] = [
  {
    prop: "l_no",
    label: "订单编号",
    width: 130
  },
  {
    prop: "l_pname",
    label: "项目名称",
    showOverflowTooltip: true
  },
  {
    prop: "jname",
    label: "技师名"
  },
  {
    prop: "l_mname",
    label: "客户名"
  },
  {
    prop: "mobile_val",
    label: "客户手机",
    width: 115
  },
  // {
  //   prop: "l_yytime",
  //   label: "提交时间",
  //   width: 160,
  //   formatter: row => formatTimestamp(row.l_yytime)
  // },
  {
    prop: "yydate_show",
    label: "预约日期",
    width: 150
  },
  {
    prop: "l_totaltime",
    label: "服务时长",
    formatter: row => formatSecondsToMinutes(row.l_totaltime)
  },
  {
    prop: "l_prices",
    label: "原价"
  },
  {
    prop: "l_amount",
    label: "实际付款"
  },
  {
    prop: "l_pay_status",
    label: "支付状态",
    width: 90,
    formatter: row => {
      const pstatus = parseInt(row.l_pay_status);
      if (isNaN(pstatus) || pstatus <= 0) return "";
      switch (pstatus) {
        case 1:
          return h(
            ElTag,
            { type: "warning", round: true, effect: "light" },
            "未支付"
          );
        case 2:
          return h(
            ElTag,
            { type: "success", round: true, effect: "dark" },
            "已支付"
          );
        default:
          return "";
      }
    }
  },
  {
    prop: "l_ystatus",
    label: "预约状态",
    width: 90,
    formatter: row => {
      const ystatus = parseInt(row.l_ystatus);
      if (isNaN(ystatus) || ystatus <= 0) return "";
      switch (ystatus) {
        case 1:
          return h(
            ElTag,
            { type: "warning", round: true, effect: "light" },
            row.yuyue_status
          );
        case 2:
          return h(
            ElTag,
            { type: "success", round: true, effect: "dark" },
            row.yuyue_status
          );
        case 3:
          return h(
            ElTag,
            { type: "danger", round: true, effect: "dark" },
            row.yuyue_status
          );
        case 4:
          return h(
            ElTag,
            { type: "info", round: true, effect: "dark" },
            row.yuyue_status
          );
        case 5:
          return h(
            ElTag,
            { type: "danger", round: true, effect: "dark" },
            row.yuyue_status
          );
        default:
          return "";
      }
    }
  },
  {
    label: "操作",
    width: 90,
    fixed: "right",
    slot: "action"
  }
];

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  if (!timestamp || timestamp === "0") return "";
  const date = new Date(parseInt(timestamp) * 1000);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 处理时间范围按钮点击
const handleTimeRangeClick = (days: number) => {
  const today = new Date();
  const endDate = today.toISOString().split("T")[0];
  const year = today.getFullYear();
  const month = today.getMonth();
  // 创建包含日期范围的搜索参数
  const searchParams = {
    start_date: `${year}-${String(month + 1).padStart(2, "0")}-01 00:00:00`,
    end_date: endDate + " 23:59:59"
  };

  handleSearch(searchParams, days);
};

// 事件处理
const handleSearch = (searchParams: any, days?: number) => {
  console.log("搜索参数:", searchParams);
  console.log("当前 searchForm:", searchForm.value);
  console.log("days 参数:", days);

  if (days !== undefined) {
    // 当点击时间范围按钮时，保留其他搜索条件，只更新日期
    const newSearchForm = {
      ...searchForm.value,
      ...searchParams
    };
    console.log("时间范围按钮 - 新的搜索表单:", newSearchForm);
    searchForm.value = newSearchForm;
  } else {
    // 当进行普通搜索时，处理日期格式
    const processedParams = { ...searchParams };

    // 如果传入的日期是 YYYY-MM-DD 格式，转换为带时间的格式
    if (
      processedParams.start_date &&
      processedParams.start_date.length === 10
    ) {
      processedParams.start_date = processedParams.start_date + " 00:00:00";
    }
    if (processedParams.end_date && processedParams.end_date.length === 10) {
      processedParams.end_date = processedParams.end_date + " 23:59:59";
    }

    // 如果传入的日期字段为空，但当前 searchForm 中有日期，则保留当前日期
    if (!processedParams.start_date && searchForm.value.start_date) {
      processedParams.start_date = searchForm.value.start_date;
    }
    if (!processedParams.end_date && searchForm.value.end_date) {
      processedParams.end_date = searchForm.value.end_date;
    }

    console.log("普通搜索 - 处理后的搜索表单:", processedParams);
    searchForm.value = processedParams;
  }

  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleView = (row: any) => {
  currentOrder.value = row;
  detailVisible.value = true;
};

// 导出数据
const handelExport = async () => {
  try {
    loading.value = true;

    // 使用当前搜索条件作为导出参数
    const exportParams = {
      start_date: searchForm.value.start_date || "",
      end_date: searchForm.value.end_date || "",
      keys: searchForm.value.keys || "",
      status: searchForm.value.status || ""
    };

    const response = await exportOrderData(exportParams);

    // 创建下载链接
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;

    // 从响应头获取文件名
    let filename = "预约订单数据.xlsx"; // 默认文件名

    if (response.headers) {
      const contentDisposition =
        response.headers["content-disposition"] ||
        response.headers["Content-Disposition"];

      if (contentDisposition) {
        // 解析 content-disposition 头，提取文件名
        // 支持多种格式：
        // attachment; filename="orders202508051534.xlsx"
        // attachment; filename=orders202508051534.xlsx
        // attachment; filename*=UTF-8''orders202508051534.xlsx
        const filenameMatch = contentDisposition.match(
          /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        );
        const filenameStarMatch = contentDisposition.match(
          /filename\*=UTF-8''([^;\n]*)/
        );

        if (filenameStarMatch && filenameStarMatch[1]) {
          // 处理 filename* 格式（支持 UTF-8 编码）
          filename = decodeURIComponent(filenameStarMatch[1]);
        } else if (filenameMatch && filenameMatch[1]) {
          // 处理普通 filename 格式
          filename = filenameMatch[1].replace(/['"]/g, ""); // 移除引号
        }
      }
    }

    // 如果没有从响应头获取到文件名，使用时间戳生成
    if (filename === "预约订单数据.xlsx") {
      const now = new Date();
      const timestamp = now.toISOString().replace(/[:.]/g, "").slice(0, -5); // 格式：20250805T1534
      filename = `预约订单数据_${timestamp}.xlsx`;
    }

    link.download = filename;

    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;

  try {
    const params: OrderListParams = {
      num: pagination.size.toString(),
      page: pagination.current.toString(),
      ...searchForm.value
    };

    // 尝试调用API
    try {
      const response = await getOrderList(params);

      if (response.code === 1) {
        tableData.value = response.data.list;
        pagination.total = response.data.total;
        return;
      } else {
        ElMessage.error(response.msg || "数据加载失败");
      }
    } catch (apiError) {
      console.error("API调用错误:", apiError);
      ElMessage.error("数据加载失败，请稍后重试");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};
const formatSecondsToMinutes = (seconds: number) => {
  if (isNaN(seconds) || seconds <= 0) return "";
  return `${seconds / 60} 分钟`;
  //return `${Math.floor(seconds / 60)} 分钟`;
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.member-management {
  height: 100%;
  background: #f5f7fa;
}

.member-detail {
  max-height: 500px;
  overflow-y: auto;
}

:deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #fafafa;
}

.dark :deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #262727;
}
</style>
